var db = wx.cloud.database()

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isData: false,
		password: '',
		search: '',
		currentTab: 0,
		watcher: null,
		size: 6,
		current: 0,
		pageSize: 6, // 每页显示的记录数量
		currentPage: 0, // 当前页码
		dataList: [],
		datacode: '',
		updataNavMessage: '',
	},

	switchChange(e) {
		let dataId = e.currentTarget.dataset.id
		let checked = e.detail.value
		console.log(checked);
		console.log(dataId);
		let originalChecked = e.currentTarget.dataset.originalChecked;
		let that = this
		wx.showModal({
			content: checked ? '标注为已发货' : '标记为未发货',
			success: function (res) {
				if (res.confirm) {
					db.collection("demouser").doc(dataId).update({
						data: {
							switchChecked: checked
						},
						success: res => {}
					})
				} else if (res.cancel) {
					// 恢复开关状态
					that.setData({
						[`dataList[${e.currentTarget.dataset.index}].switchChecked`]: originalChecked
					});
					console.log('用户点击取消');
				}
			},
			fail: function () {}
		})
	},

	// 监听数据是否发生变化，是否需要下拉加载
	startWatch: function () {
		const collection = db.collection('demouser'); // 替换为实际的集合名称
		this.data.watcher = collection.watch({
			onChange: snapshot => {
				let dataType = snapshot.docChanges[0].dataType
				let datacode = snapshot.docChanges[0].doc.code
				let exampleObject = snapshot.docChanges[0].updatedFields
				let targetKeys = ['shengshiqu', 'userlocal', 'username', 'usernumber'];
				let hasOneKey = false
				if (exampleObject !== undefined) {
					let objectKeys = Object.keys(exampleObject);
					hasOneKey = targetKeys.some(key => objectKeys.includes(key));
					if (dataType == 'update') {
						if (hasOneKey) {
							console.log('数据发生变化:', snapshot);
							this.setData({
								updataNavMessage: `有一条卡密为${datacode}的发货订单信息发生了变更,请及时下拉进行刷新查看(可长按此条消息即可复制卡密)`,
								datacode: datacode
							})
						}
					}
				}
			},
			onError: err => {
				console.error('监听失败:', err);
			}
		});
	},
	getData(e) {
		if (e == 0) {
			this.setData({
				dataList: []
			})
		}
		let skip = this.data.currentPage * this.data.pageSize;
		let limit = this.data.pageSize;
		db.collection("demouser")
			.skip(skip)
			.limit(limit)
			.where({
				switchChecked: this.data.currentTab == 0 ? false : true
			}).get({
				success: res => {
					let newData = res.data;
					if (newData.length == 0) {
						this.setData({
							showChuDi: true
						})
					}
					let oldData = this.data.dataList;
					this.setData({
						dataList: oldData.concat(newData), // 将新数据追加到原数据列表
						currentPage: this.data.currentPage + 1 // 更新当前页码
					});
				}
			})
	},
	searIpt(e) {},
	passwordIpt() {},
	searchData() {
		let that = this
		that.setData({
			currentPage: this.data.current,
			pageSize: this.data.size,
			isData: false,
			showChuDi: false
		})
		if (this.data.search == "") {
			this.getData(0)
			return
		}
		wx.showLoading({
			title: '正在加载中',
			mark: true
		})
		let skip = this.data.currentPage * this.data.pageSize;
		let limit = this.data.pageSize;
		db.collection('demouser').where({
				code: this.data.search,
				switchChecked: this.data.currentTab == 0 ? false : true
			})
			.skip(skip)
			.limit(limit)
			.get({
				success: function (res) {
					wx.hideLoading()
					that.setData({
						dataList: res.data
					})
					if (res.data.length == 0) {
						that.setData({
							isData: true
						})
					}
				}
			})
	},
	copyText(e) {
		let key = e.currentTarget.dataset.key;
		wx.setClipboardData({ //设置系统剪贴板的内容
			data: key,
			success(res) {
				console.log(res, key);
				wx.getClipboardData({ // 获取系统剪贴板的内容
					success(res) {
						wx.showToast({
							title: '复制成功',
						})
					}
				})
			}
		})
	},
	copyContent(e) {
		let key = e.currentTarget.dataset.key;
		let copyText =
			`
卡密：${key.code}
姓名：${key.username}
电话：${key.usernumber}
地址：${key.shengshiqu}${key.userlocal}
`
		wx.setClipboardData({
			data: copyText,
			success(res) {
				wx.getClipboardData({
					success(res) {
						wx.showToast({
							title: '复制成功',
						})
					}
				})
			}
		})
	},
	swichNav(e) {
		this.setData({
			currentPage: this.data.current,
			pageSize: this.data.size,
			isData: false,
			showChuDi: false,
			search: ''
		})
		let skip = this.data.currentPage * this.data.pageSize;
		let limit = this.data.pageSize;
		var that = this;
		if (this.data.currentTab === e.target.dataset.current) {
			return false;
		} else {
			that.setData({
				currentTab: e.target.dataset.current
			})
			wx.showLoading({
				title: '正在加载中',
				mark: true
			})
			db.collection('demouser').where({
					switchChecked: e.target.dataset.current == 0 ? false : true
				})
				.skip(skip)
				.limit(limit)
				.get({
					success: function (res) {
						wx.hideLoading()
						that.setData({
							dataList: res.data
						})
						console.log(res.data);
						if (res.data.length == 0) {
							that.setData({
								isData: true
							})
						}
					}
				})
		}
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		this.getData()
		this.startWatch()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显z示
	 */
	onShow() {},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},
	restPage() {
		this.setData({
			updataNavMessage: '',
			currentPage: this.data.current,
			pageSize: this.data.size,
			search: ''
		})
	},
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {
		this.restPage()
		this.getData(0)
		wx.stopPullDownRefresh()
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {
		console.log(this.data.currentTab);
		if (this.data.currentPage == 0) {
			this.setData({
				currentPage: 1
			})
			this.getData()
		} else {
			this.getData()
		}
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})